<template>
    <view class="content bg_com">
        <!-- 顶部搜索 -->
        <com-nav-bar>
            <template>
                <uni-nav-bar class="nav_bar"
                             left-icon="back"
                             color="#F1EDFF"
                             backgroundColor="#181526"
                             left-text="消息"></uni-nav-bar>
            </template>
        </com-nav-bar>

        <scroll-view class="conversations"
                     scroll-y="true">
            <view class="scroll-item"
                  v-for="(item, key) in p2pMsgArr"
                  :key="key"
                  @click="handleIntoMsgDetail(item)">
                <view class="item-head">
                    <image :src='item.avatar'
                           class="head-icon"></image>
                </view>
                <view class="scroll-item_info">
                    <view class="item-info-top">
                        <text class="item-info-top_name">{{item.nick}}</text>
                        <view class="item-info-top_time">{{timesub(item.updateTime)}}</view>
                    </view>
                    <view class="item-info-bottom">
                        <view class="item-info-bottom-item">
                            <view class="item-info-top_content">
                                {{item.lastMsg.text}}</view>
                            <view v-if="item.unread != 0"
                                  class="item-info-bottom_action">{{item.unread}}</view>
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>

        <view class="msgBox">
            <uni-popup ref="popupP2pMsgs"
                       type="right">
                <view class="MsgCotainer">
                    <view class="detail">
                        <view class="detail-tip">
                            <image class="back"
                                   src="../../../static/qert.png"
                                   @click="handBackToP2PList"></image>
                            <text class="userNick">{{detailMsgSession.other.nick}}</text>
                        </view>

                        <scroll-view class="msg_scroll"
                                     scroll-y="true"
                                     :scroll-top="msgScrollTop">
                            <view :class="{ 'detail-item': true , 'detail-mine' : item.isMineFlag}"
                                  v-for="(item,index) in detailMsgSession.msgs"
                                  :key="index">
                                <!-- <view class="time">07-09 17:12</view> -->
                                <div class="detail-content">
                                    <image class="user-icon"
                                           :src='item.isMineFlag ? item.mine.avatar: item.other.avatar '></image>
                                    <view class="msg">
                                        {{item.text}}
                                    </view>
                                </div>
                            </view>
                        </scroll-view>
                        <view class="sendBox">
                            <input type="text"
                                   placeholder="请输入..."
                                   placeholder-style="color:#E5DDFF"
                                   v-model="p2pVal"
                                   @confirm="sendP2PMsg">
                            <button class="sendBtn"
                                    @click="sendP2PMsg">发送</button>
                        </view>
                    </view>
                </view>
            </uni-popup>
        </view>
    </view>
</template>

<script>
import {
    mapState
} from 'vuex';
import NIM from '../../../house/libs/NIM_Web_NIM_miniapp_v8.9.0'
// const appKey = '9bbedb58f17bba7bbf3256f43c8cab91' //云信appKey
let nimInstance
export default {
    computed: mapState(['hasLogin', 'user', 'identity', 'tickets']),
    data() {
        return {
            p2pMsgArr: [],
            msgScrollTop: 0,
            detailMsgSession: [],
            p2pVal: ''
        }
    },
    onShow() {
        console.log('onshow')
		if(this.hasLogin) {
			this.initNIM();
		}
    },
	onLoad() {
		if(!this.hasLogin) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		}
	},
    methods: {
        //初始化云信账号
        initNIM() {
            const {
                uid,
                netEaseToken
            } = this.identity;
            var _nim = NIM.getInstance({
                debug: false, // 是否开启日志，将其打印到console。集成开发阶段建议打开。
                appKey: this.$urlConfig.appKey,
                account: uid,
                token: netEaseToken,
                db: true, //若不要开启数据库请设置false。SDK默认为true。
                onsessions: async (sessions) => {
                    let p2pTextMsgs = nimInstance.mergeSessions(this.p2pMsgArr, sessions)
                    p2pTextMsgs = p2pTextMsgs.filter(ele => ele.scene == 'p2p' && ele.lastMsg.type == 'text');
                    for (let i in p2pTextMsgs) {
                        await this.$api.userDetail({
                            uid: this.identity.uid,
                            ticket: this.tickets[0].ticket,
                            targetUid: sessions[i].to,

                        }).then((res) => {
                            p2pTextMsgs[i].avatar = res.data.avatar;
                            p2pTextMsgs[i].nick = res.data.nick;
                        })
                    }
                    this.p2pMsgArr = p2pTextMsgs;
                },
                onupdatesession: async (sessions) => {
                    if (this.p2pMsgArr.find(i => i.to == sessions.to)) {
                        this.$set(this.p2pMsgArr, this.p2pMsgArr.findIndex(i => i.to == sessions.to), {
                            ...this.p2pMsgArr.find(i => i.to == sessions.to),
                            ...sessions,
                        })
                        if (sessions.lastMsg.from != this.identity.uid) {
                            if (this.detailMsgSession && this.detailMsgSession.msgs) {
                                this.detailMsgSession.msgs.push({
                                    ...sessions.lastMsg,
                                    mine: this.user,
                                    other: this.detailMsgSession.other,
                                    isMineFlag: false,
                                })
                                //滚动到底部
                            }
                            this.msgScrollTop += 80
                        }

                    }

                    let p2pTextMsgs = nimInstance.mergeSessions(this.p2pMsgArr, sessions)
                    p2pTextMsgs = p2pTextMsgs.filter(ele => ele.scene == 'p2p' && ele.lastMsg.type == 'text');
                    console.log(p2pTextMsgs)
                    for (let i in p2pTextMsgs) {
                        await this.$api.userDetail({
                            uid: this.identity.uid,
                            ticket: this.tickets[0].ticket,
                            targetUid: p2pTextMsgs[i].to,

                        }).then((res) => {
                            p2pTextMsgs[i].avatar = res.data.avatar;
                            p2pTextMsgs[i].nick = res.data.nick;
                        })
                    }
                    console.log('onupdatesession', p2pTextMsgs)
                    this.p2pMsgArr = p2pTextMsgs;
                },
            });
            nimInstance = _nim;

        },
        timesub(time) {
            var date = new Date(time);
            var year = date.getFullYear();
            var mou = date.getMonth() + 1;
            var day = date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var myDate = new Date();
            var newdate = (myDate.getMonth() * 30) + myDate.getDate();
            var thisdate = (mou * 30) + day;
            hours < 10 ? hours = '0' + hours : null;
            minutes < 10 ? minutes = '0' + minutes : null;
            day < 10 ? day = '0' + day : null;
            mou < 10 ? mou = '0' + mou : null;
            if (myDate.getFullYear() != year) {
                var newtime = year + '-' + mou + '-' + day + ' ' + hours + ':' + minutes;
            } else if (newdate - thisdate > 2) {
                var newtime = mou + '-' + day + ' ' + hours + ':' + minutes;
            } else if (newdate - thisdate == 2) {
                var newtime = '前天 ' + hours + ':' + minutes;
            } else if (newdate - thisdate == 1) {
                var newtime = '昨天 ' + hours + ':' + minutes;
            } else {
                var newtime = hours + ':' + minutes;
            }
            return newtime;
        },

        handleIntoMsgDetail(item) { //聊天详情
            // uni.navigateTo({
            //     url: '/pages/tabBar/message/messageDetails?item=' + JSON.stringify(item)
            // });
            // return
            nimInstance.setCurrSession(item.id)
            //滚动到底部
            nimInstance.getHistoryMsgs({
                scene: 'p2p',
                to: item.to,
                reverse: true,
                done: (err, obj) => {
                    console.log('获取具体聊天记录', obj, obj.msgs)
                    this.detailMsgSession = {
                        ...obj,
                        mine: this.user,
                        other: item,
                        msgs: obj.msgs.map(msg => {
                            return {
                                ...msg,
                                mine: this.user,
                                other: item,
                                isMineFlag: msg.from == this.user.uid
                            }
                        }),
                        _item: item
                    }
                    uni.hideTabBar()
                    this.open();
                    setTimeout(() => {
                        this.msgScrollTop = this.detailMsgSession.msgs.length * 80;
                    }, 500);

                }
            });
        },
        open() {
            this.$refs.popupP2pMsgs.open();
        },
        close() {
            this.$refs.popupP2pMsgs.close();
        },
        sendP2PMsg() {
            nimInstance.sendText({
                scene: 'p2p',
                to: this.detailMsgSession.other.to,
                text: this.p2pVal,
                done: (error, msg) => {
                    //滚动到底部
                    this.p2pVal = ''
                    this.detailMsgSession.msgs.push({
                        ...msg,
                        mine: this.user,
                        other: this.detailMsgSession.other,
                        isMineFlag: true,
                    })
                    this.msgScrollTop += 80
                }
            });
        },
        handBackToP2PList() {
            console.log(this.detailMsgSession)
            nimInstance.resetCurrSession()
            this.detailMsgSession = {},
                this.close();
            uni.showTabBar();
        },
    },
    onHide() {
        console.log('onhide')
        nimInstance && nimInstance.destroy()
    }
}
</script>

<style lang="scss">
@import "./index.scss";
</style>
